package com.erji.admin.service.impl;

import cn.hutool.json.JSONObject;
import com.erji.admin.config.WechatApiConfig;
import com.erji.admin.domain.dto.AppletBindDTO;
import com.erji.admin.domain.dto.AppletLoginDTO;
import com.erji.admin.domain.dto.AppletLoginUser;
import com.erji.admin.domain.entity.AppletUserLoginLogPO;
import com.erji.admin.domain.entity.AppletUserPO;
import com.erji.admin.domain.vo.AppletLoginResultVO;
import com.erji.admin.domain.vo.AppletUserVO;
import com.erji.admin.exception.SysErrorCode;
import com.erji.admin.mapper.AppletUserMapper;
import com.erji.admin.service.AppletTokenService;
import com.erji.admin.service.AppletUserLoginLogService;
import com.erji.admin.service.AppletUserService;
import com.erji.admin.utils.AppletRequestUtils;
import com.erji.common.constant.Constants;
import com.erji.common.mybatis.persistence.SuperServiceImpl;
import com.erji.common.utils.Assert;
import com.erji.common.utils.SecurityUtils;
import com.erji.common.utils.ip.IpUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 *
 * @Author Lynkin
 * @Date 2023/12/17
 */
@Service
public class AppletUserServiceImpl extends SuperServiceImpl<AppletUserMapper, AppletUserPO> implements AppletUserService {

    private static final Logger log = LoggerFactory.getLogger(AppletUserServiceImpl.class);

    @Autowired
    private WechatApiConfig wechatApiConfig;

    @Autowired
    private AppletTokenService appletTokenService;

    @Autowired
    private AppletUserLoginLogService memberLoginLogService;


    /**
     * 会员绑定
     *
     * @param appletBindDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void bind(AppletBindDTO appletBindDTO) {
        String userId = SecurityUtils.getUserId();
        AppletUserPO memberPO = fetchById(userId);
        Assert.notNull(memberPO, SysErrorCode.MEMBER_NOT_EXIST);
        facade.map(appletBindDTO, memberPO);
        updateById(memberPO);
    }


    /**
     * @Author Lynkin
     * @Description 会员小程序登录
     * @Date 2023/12/17
     * @Param [jsCode]
     * @return com.ivnin.system.domain.vo.AppletLoginResultVO
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AppletLoginResultVO login(AppletLoginDTO appletLoginDTO) {

        // 获取session_key和openid
        String result = AppletRequestUtils.getOpenIdByCode(wechatApiConfig.getAppId(), wechatApiConfig.getSecret(), appletLoginDTO.getJsCode());

        log.info("调用微信登录返回----------------------------------->{}", result);

        // 提取openid
        String openId = new JSONObject(result).getStr("openid");
        String unionId = new JSONObject(result).getStr("unionid");
        String sessionKey = new JSONObject(result).getStr("session_key");

        Assert.notNull(openId, SysErrorCode.WECHAT_API_ERROR);

        AppletUserVO memberVO = mapper.findByOpenId(openId);

        // openid不存在
        if (ObjectUtils.isEmpty(memberVO)) {
            // 添加用户
            AppletUserPO memberPO = new AppletUserPO();
            memberPO.setOpenId(openId);
            memberPO.setUnionId(unionId);
            memberPO.setUsername("为邻邻友");
            memberPO.setStatus(1);
            AppletUserPO savePO = save(memberPO);
            memberVO = facade.map(savePO, AppletUserVO.class);
        }
        //返回登录token
        AppletLoginUser appletLoginUser = new AppletLoginUser();
        appletLoginUser.setUserId(memberVO.getId());
        appletLoginUser.setUserName(memberVO.getUsername());
        String token = appletTokenService.createToken(appletLoginUser);

        //记录用户的登录日志
        AppletUserLoginLogPO memberLoginLogPO = new AppletUserLoginLogPO();
        memberLoginLogPO.setMemberId(memberVO.getId());
        memberLoginLogPO.setLoginType(3);
        memberLoginLogPO.setIp(IpUtils.getIpAddr());
        memberLoginLogPO.setStatus(Constants.LOGIN_SUCCESS_STATUS);
        memberLoginLogService.create(memberLoginLogPO);

        return new AppletLoginResultVO(sessionKey, openId, unionId, token);
    }

    /**
     * 获取当前登录会员信息
     *
     * @return
     */
    @Override
    public AppletUserVO getAppletUserInfo() {
        String userId = SecurityUtils.getUserId();
        AppletUserPO appletUserPO = fetchById(userId);
        Assert.notNull(appletUserPO, SysErrorCode.MEMBER_NOT_EXIST);
        AppletUserVO appletUserVO = facade.map(appletUserPO, AppletUserVO.class);
        return appletUserVO;
    }


    /**
     * 小程序获取手机号
     *
     * @param appletLoginDTO
     * @return
     */
    @Override
    public Map<String, String> getPhoneNumber(AppletLoginDTO appletLoginDTO) {
        JSONObject phoneNumberInfo = AppletRequestUtils.getPhoneNumber(wechatApiConfig.getAppId(), wechatApiConfig.getSecret(), appletLoginDTO.getJsCode());
        HashMap<String, String> result = new HashMap<>();
        result.put("phoneNumber", phoneNumberInfo.get("phone_info", JSONObject.class).getStr("phoneNumber"));
        result.put("purePhoneNumber", phoneNumberInfo.get("phone_info", JSONObject.class).getStr("purePhoneNumber"));
        result.put("countryCode", phoneNumberInfo.get("phone_info", JSONObject.class).getStr("countryCode"));
        //返回信息
        return result;
    }
}
